import React, { useEffect, useState } from "react";
import request from "@/services/interceptors";
import { Image } from "antd";

const BackendImage = ({ url }: { url: string }) => {
  const [imgSrc, setImgSrc] = useState<string>("");

  useEffect(() => {
    if (!url) return;
    let revokeUrl: string | null = null;
    const getfile = async (url: string) => {
      // 关键：设置 responseType 为 blob
      const res: any = await request.sgks.fileDownloadList(
        {
          relativePath: url,
        },
        {
          format: "blob",
        }
      );
      // 兼容不同后端返回格式
      const downloadUrl = URL.createObjectURL(res.data);
      setImgSrc(downloadUrl);
      revokeUrl = downloadUrl;
    };
    getfile(url);

    // 组件卸载时释放 URL
    return () => {
      if (revokeUrl) {
        URL.revokeObjectURL(revokeUrl);
      }
    };
  }, [url]);

  if (!imgSrc) return null;

  return <Image src={imgSrc} alt="" />;
};

export default BackendImage;
